/*
 * 描          述:  <描述>
 * 修  改   人:  PengQingyang
 * 修改时间:  2022年4月26日
 * <修改描述:>
 */
package com.tx.component.sendsms.plugin.aliyun;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.dysmsapi20170525.models.SendSmsResponseBody;
import com.aliyun.teaopenapi.models.Config;
import com.tx.component.communication.exceptions.SendSMSException;
import com.tx.component.communication.model.SendResult;
import com.tx.component.sendsms.model.SendSMSWTChannelEnum;
import com.tx.component.sendsms.model.SendSMSWithTemplateRequest;
import com.tx.component.sendsms.plugin.SendSMSPlugin;
import com.tx.component.sendsms.plugin.SendSMSWithTemplateHandler;
import com.tx.core.exceptions.util.AssertUtils;

/**
 * 阿里云短信发送插件<br/>
 * <功能详细描述>
 * 
 * @author  PengQingyang
 * @version  [版本号, 2022年4月26日]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class AliyunSendSMSPlugin
        extends SendSMSPlugin<AliyunSendSMSPluginConfig>
        implements SendSMSWithTemplateHandler {
    
    /** 默认的链接超时时间 */
    private static final int DEFAULT_CONNNECT_TIMEOUT = 15 * 1000;
    
    /** 默认的读取超时时间 */
    private static final int DEFAULT_READ_TIMEOUT = 20 * 1000;
    
    /** 短信发送客户端 */
    private Client client;
    
    /**
     * @throws Exception
     */
    @Override
    protected void doInit() throws Exception {
        AliyunSendSMSPluginConfig config = getConfig();
        this.client = createClient(config.getAccessKeyId(),
                config.getAccessKeySecret());
    }
    
    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public Client createClient(String accessKeyId, String accessKeySecret)
            throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret)
                //设置connectTimeout
                .setConnectTimeout(DEFAULT_CONNNECT_TIMEOUT)
                //设置readTimeout
                .setReadTimeout(DEFAULT_READ_TIMEOUT);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new Client(config);
    }
    
    /**
     * @return
     */
    @Override
    public String getPrefix() {
        return "plugin.sendSMS.aliyun";
    }
    
    /**
     * @return
     */
    @Override
    public String getName() {
        return "阿里云短信插件";
    }
    
    /**
     * @return
     */
    @Override
    public String getVersion() {
        return "1.0";
    }
    
    /**
     * @return
     */
    @Override
    public int getOrder() {
        AliyunSendSMSPluginConfig config = getConfig();
        return config.getPriorty();
    }
    
    /**
     * 使用阿里云发送短信<br/>
     * @param request
     * @return
     */
    @Override
    public boolean supports(SendSMSWithTemplateRequest request) {
        if (SendSMSWTChannelEnum.ALIYUN.equals(request.getChannel())) {
            return true;
        }
        return false;
    }
    
    /**
     * @param request
     * @return
     */
    @Override
    public SendResult sendWithTemplate(SendSMSWithTemplateRequest request) {
        AssertUtils.notNull(request, "request is null.");
        AssertUtils.notNull(request.getChannel(), "request.channel is null.");
        
        //电话号码、模板号、签名不能为空
        AssertUtils.notEmpty(request.getPhoneNumbers(),
                "request.phoneNumbers is empty.");
        AssertUtils.notEmpty(request.getTemplateCode(),
                "request.pemplateCode is empty.");
        AssertUtils.notEmpty(request.getSignName(),
                "request.signName is empty.");
        
        //构建请求
        SendSmsRequest aliyunReq = new SendSmsRequest()
                .setPhoneNumbers(request.getPhoneNumbers())
                .setTemplateCode(request.getTemplateCode())
                .setSignName(request.getSignName())
                .setTemplateParam(request.getTemplateParamJSONString());
        
        //发送请求，并生成发送结果
        try {
            SendSmsResponse response = client.sendSms(aliyunReq);
            SendSmsResponseBody body = response.getBody();
            //Code  String  OK  状态码。返回OK代表请求成功，其他错误码详见错误码列表。
            //Message   String  请求成功    状态码的描述。
            //RequestId String  8906582E-6722   请求ID。
            //BizId String  134523^4351232  发送回执ID，可根据该ID查询具体的发送状态。
            if (AliyunSendSMSResponseCodeEnum.OK.getCode()
                    .equals(body.getCode())) {
                SendResult result = SendResult.newSuccess();
                result.setMessage(body.getMessage());
                result.getAttributes().put("RequestId", body.getRequestId());
                result.getAttributes().put("BizId", body.getBizId());
                return result;
            } else {
                SendResult result = SendResult.newFail(body.getMessage());
                return result;
            }
        } catch (Exception e) {
            throw new SendSMSException(e.getMessage(), e);
        }
    }
    
}
